<?php

if (!defined('__COLA_DIR__')) exit;

/**
 * 开启框架模块
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Start extends Cola
{

    /**
     * 构造函数,初始化组件
     *
     * @access public
     * @param mixed $request request对象
     * @param mixed $response response对象
     * @param mixed $params 参数列表
     */
    public function __construct($request, $response, $params = NULL)
    {
        parent::__construct($request, $response, $params);

		/** 插件接口 */
        //HOOK PLUG_Start($this);

        /** 对变量赋值 */
        $options = $this->widget('Widget_Options');
        
        if (defined('__COLA_PATHINFO_ENCODING__')) {
            $pathInfo = $this->request->getPathInfo(__COLA_PATHINFO_ENCODING__, $options->charset);
        } else {
            $pathInfo = $this->request->getPathInfo();
        }

		/** 设置路径 */
        Router::setPathInfo($pathInfo);

        /** 初始化路由器 */
        Router::set($options->routingTable);
		
        /** 冲刷掉已经存在的输出 */
        if (ob_get_length() > 0) {
            $this->response->write(ob_get_clean());
        }
		
        /** 对AJAX请求关闭缓存 */
        if ($this->request->isAjax()) {
            $this->response->cache(false);
        }
		
		/** 监听缓冲区 */
        ob_start();
		
		/** 设置异常截获函数 */
		
	    /** 插件接口 */
		//HOOK {$plugged} PLUG_SetErrorHandler($this);
        if (!$plugged) {
            set_error_handler(array($this, 'handleError'));
        }
		
	    /** 插件接口 */
		//HOOK {$plugged} PLUG_SetExceptionHandler($this);
        if (!$plugged) {
            set_exception_handler(array($this, 'handleException'));
        }
    }

    /**
     * 入口函数
     *
     * @access public
     * @return void
     */
    public function execute()
    {
		/** 插件接口 */
		//HOOK PLUG_Begin($this);

        /** 开始路由分发 */
        Router::dispatch();

		/** 插件接口 */
		//HOOK PLUG_End($this);
		
		$this->response
		    ->status(200)
		    ->write(ob_get_clean())
		    ->send();
    }
	
    /**
     * Custom error handler. Converts errors into exceptions.
     *
     * @param int $errno Error number
     * @param int $errstr Error string
     * @param int $errfile Error file name
     * @param int $errline Error file line number
     * @throws ErrorException
     */
    public function handleError($errno, $errstr, $errfile, $errline) 
	{
        if ($errno & error_reporting()) {
            throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
        }
    }

    /**
     * Custom exception handler. Logs exceptions.
     *
     * @param object $e Thrown exception
     */
    public function handleException($e) 
	{
        if (!Common::$debug && 404 == $e->getCode()) {
		    $this->widget('Widget_Archive@404', 'type=404')->render();
        } else {
            $this->widget('Widget_Error')->set($e);
        }
    }
}
